<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('CurrencyModel')) return;
/**
 * EcataloguE
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage ecatalogue
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/EcataloguE
 */

/**
 *  CurrencyModel class 
 *  
 *  Some conventions:
 *  Current currency - currency, in wich all prices are outputed for user. Exception can be done for products prices - if output currency is set via rubrique, it's price will be outputed in it. 
 *  Main currency - currency, in wich all prices are stored in DB. Exception can be done in extensions (e.g. Shipping Flat, wich allows to store it's cost in any currency)
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
include_spip('classes/pdk_model'); 
//include_spip('functions/pdk_common');
class CurrencyModel extends pdk_Model {   
    /**
     *  RubriqueCurrencyModel
     */
    private $rub_cur_mdl;
    
    /**
     *  PdkRubriqueModel
     */
    private $rub_mdl;
    
    /**
     *  PdkArticleModel
     */
    private $art_mdl;
    
    /**
     *  Current currency ID, wich is stored on session
     */
    private $current_currency_id;
    
    /**
     *  Main currency ID (rate=1)
     */
    public $main_currency_id;
    
    public $price_precision;
        
    public function __construct() {
        parent::__construct();
        
        $this->config_model();
        include_spip('functions/pdk_common');
        $this->rub_cur_mdl = pdk_load_class('RubriqueCurrencyModel','classes');        
        $this->rub_mdl = pdk_load_class('PdkRubriqueModel','classes/models');
        $this->art_mdl = pdk_load_class('PdkArticleModel','classes/models');
        
        include_spip('classes/class.EcatalogueException');
        
        $this->config_currencies();
        
        $this->price_precision = lire_config('ecatalogue/price_pricision'); if (!$this->price_precision) $this->price_precision = 2;
    }
    
    function config_model() {
        // Define main table:
        $this->main_table = 'spip_ecatalogue_currencies';
        
        // Define primary key:
        $this->primary_key = 'id_currency';
        
        // Define main table fields:
        $this->main_fields['id_currency'] = 'id_currency'; 
        $this->main_fields['titre'] = 'titre';        
        $this->main_fields['sign_pre'] = 'sign_pre';
        $this->main_fields['sign_after'] = 'sign_after';
        $this->main_fields['code'] = 'code';
        $this->main_fields['rate'] = 'rate';
                                                                                 
         // Define validation rules:
         $this->validation->set_rules( 
            array(
                array(
                     'field'   => 'id_currency',
                     'label'   => 'ID currency',
                     'rules'   => ''
                  ),
                array(
                     'field'   => 'titre',
                     'label'   => _T('ecatalogue:currency_titre'),
                     'rules'   => 'required'
                  ),
                array(
                     'field'   => 'sign_pre',
                     'label'   => _T('ecatalogue:currency_sign_pre'),
                     'rules'   => ''
                  ),    
                array(
                     'field'   => 'sign_after',
                     'label'   => _T('ecatalogue:currency_sign_after'),
                     'rules'   => ''
                  ),  
                array(
                     'field'   => 'code',
                     'label'   => _T('ecatalogue:currency_code'),
                     'rules'   => 'required'
                  ),  
                array(
                     'field'   => 'rate',
                     'label'   => _T('ecatalogue:currency_rate'),
                     'rules'   => 'required'
                  ),  
            )
         );                                       
    }
    
    protected function config_currencies() {
        $currency = $this->select('rate=1');                        
        if ($currency)
            $this->main_currency_id = $currency[0]['id_currency'];
        else 
            throw new EcatalogueException('There are no currency with rate=1!');
        
        @session_start();
        $this->current_currency_id = &$_SESSION["current_currency_id"];
        if (!isset($this->current_currency_id) && !$this->current_currency_id) {
            $this->current_currency_id = $this->main_currency_id;
        }
        
        
    }
    
    // Define test data
    public $test_data = array(
        array('id_currency'=>1,'titre'=>'<multi>[ru]Доллар США[en]U.S. Dollar</multi>', 'sign_pre'=>'$', 'sign_after'=>'', 'code'=>'USD', 'rate'=>'0.125'),
        array('id_currency'=>2,'titre'=>'<multi>[ru]Украинская гривна[en]Ukrainian hryvnia</multi>', 'sign_pre'=>'', 'sign_after'=>'hrn','code'=>'UAH', 'rate'=>'1'),
        array('id_currency'=>3,'titre'=>'<multi>[ru]Євро[en]Euro</multi>', 'sign_pre'=>'€', 'sign_after'=>'', 'code'=>'EUR', 'rate'=>'0.0958'),
    );
    
    public function SelectByCode($code) {
        $currency = $this->select("code='".mysql_real_escape_string($code)."'");
        if ($currency)
            return $currency[0];
        else
            return false;     
    } 
    
    /**
     *  Finds currency for given rubrique
     *  This method takes to account currency inheritance possibility
     *  If no currency where found, current currency will be returned
     *  @access public
     *  @param int $id_rubrique ID rubrique
     *  @return Currency array if currency for given rubrique exists or current currency otherwise
     */
    public function GetCurrencyByIdRubrique($id_rubrique) {        
        // Get link for given rubrique
        // If link exists, return currency
        $rub_cur = $this->rub_cur_mdl->select('id_rubrique='.$id_rubrique);        
        if ($rub_cur) {
            $rub_cur = $rub_cur[0];
            return $this->select_by_id($rub_cur['id_currency']);
        }
                
        $rubrique = $this->rub_mdl->select_by_id($id_rubrique);
        // Get link for parent rubrique
        $rub_cur = $this->rub_cur_mdl->select('id_rubrique='.$rubrique['id_parent']);
        // If link for parent rubrique exists, return currency       
        if ($rub_cur) {
            $rub_cur = $rub_cur[0];
            return $this->select_by_id($rub_cur['id_currency']);
        }
        // If our rubrique has parent, make a recursive call
        if ($rubrique['id_parent'] != 0)
            return $this->GetCurrencyByIdRubrique($rubrique['id_parent']);
        
        //return false;
        return $this->GetCurrentCurrency();
    }
    
    /**
     *  Finds currency for given article
     *  This method takes to account currency inheritance possibility
     *  @access public
     *  @param int $id_article ID article
     *  @return Currency array if currency for given rubrique exists or false otherwise
     */
    public function GetCurrencyByIdArticle($id_article) {
        $article = $this->art_mdl->select_by_id($id_article);        
        if (!$article['id_rubrique']) return false;
        
        return $this->GetCurrencyByIdRubrique($article['id_rubrique']);
    }
    
    /**
     *  Gets currency sign by id article
     *  @param int $id_article ID article
     *  @param string $sign Sign field (sign_pre or sign_after). Default: sign_pre
     */
    public function GetCurrencySignByIdArticle($id_article, $sign='sign_pre') {
        $currency = $this->GetCurrencyByIdArticle($id_article);
        if (!$currency) return false;
        
        if (!isset($currency[$sign]))
            throw new EcatalogueException("Currency field \"$sign\" doesn't exist!");
        
        return $currency[$sign];   
    }
    
    /**
     *  Gets current currency
     *  @return array Currency as row of currencies table  
     */
    public function GetCurrentCurrency() {
        if (!isset($this->current_currency_id) || !$this->current_currency_id)
            throw new EcatalogueException("Current currency wasn't set!");
        return $this->select_by_id($this->current_currency_id);        
    }
    
    /**
     *  Gets current currency ID
     */
    public function GetCurrentCurrencyId() {
        $currency = $this->GetCurrentCurrency();
        if ($currency)
            return $currency['id_currency']; 
    }
	
	/**
     *  Gets current currency code
     */
    public function GetCurrentCurrencyCode() {
        $currency = $this->GetCurrentCurrency();
        if ($currency)
            return $currency['code']; 
    }
    
    /**
     *  Sets current currency ID
     *  @param int $id_currency ID currency to set as current. If false, current currency will be deleted 
     */
    public function SetCurrentCurrencyId($id_currency = false) {
        if (!isset($id_currency) || !$id_currency) 
            unset($this->current_currency_id);
        else     
            $this->current_currency_id = $id_currency;            
    }
    
    /**
     *  Converts given price into current currency (see GetCurrentCurrency())) from main currency (rate=1)
     */
    public function ConvertPriceToCurrentCurrency($price) {
        $cur_currency = $this->GetCurrentCurrency();
        if ($cur_currency['rate'])
            return round($cur_currency['rate']*$price, $this->price_precision);
        return 0;     
    }
    
    /**
     *  Converts price to main currency (rate=1)
     */
    public function ConvertPriceToMainCurrency($price, $id_currency_from) {
        return $this->ConvertPrice($price, $id_currency_from, $this->main_currency_id);
    }
    
    /**
     *  Gets main currency
     */
    public function GetMainCurrency() {
        if (!isset($this->main_currency_id) || !$this->main_currency_id)
            throw new EcatalogueException("Main currency wasn't set!");
        return $this->select_by_id($this->main_currency_id);
    }  
    
    /**
     *  Gets main currency ID
     */
    public function GetMainCurrencyId() {
        $currency = $this->GetMainCurrency();
        if ($currency)
            return $currency['id_currency']; 
    }
    
    /**
     *  Converts given price from one currency to another
     *  @param float $price Price
     *  @param int $id_currency_from
     *  @param int $id_currency_to If not given, price will be converted into current currency
     */
    public function ConvertPrice($price, $id_currency_from, $id_currency_to = false) {
        $currency_from = $this->select_by_id($id_currency_from);
        if (!$currency_from) 
            throw new EcatalogueException("Can't find currency #".$id_currency_from);
        if (isset($id_currency_to) && $id_currency_to) {
            $currency_to = $this->select_by_id($id_currency_to);         
            if (!$currency_to) 
                throw new EcatalogueException("Can't find currency #".$id_currency_to);    
        } else {
            $currency_to = $this->GetCurrentCurrency();
        } 
        $price = $price*$currency_to['rate']/$currency_from['rate'];
        return round($price, $this->price_precision) ;
    }
} 
?>